
import { IUser, ILoginUser } from '../model/user';
import tools from '../common/tools';
import wxService from '../common/wxService';
import { config } from '../etc/config'
import httpClient from '../common/http-client'
import { MlcEnum } from '../model/enum';
import * as wux from '../assets/components/wux'
export module UserAuth {
	export function checkLogin() {
		const user = wx.getStorageSync("userInfo") as IUser;
		return user && user != "" && user.token && user.token != "";
	}

	export function getUserInfo() {
		const user = wx.getStorageSync("userInfo") as IUser;
		return user
	}

	export function checkIsBuy(): boolean {
		const user = this.getUserInfo();
		if (!user.isVip) {
			wux.dialog.open({
				title: '温馨提示',
				content: '您还未进行信息认证！',
				buttons: [
					{
						text: '知道了',
					},
					{
						text: '去认证',
						type: 'weui-dialog__btn_primary',
						onTap(e) {
							wxService.navigateTo('/pages/cert/auth/index?formOrder=true')
						},
					},
				]
			});
			return false;
		} else if (user.status == MlcEnum.UserEnterpriseStatus.等待审核) {
			wux.dialog.alert({
				title: '温馨提示', 
				content: '您的认证信息正在审核中,暂不能购买', 
				confirmText:'知道了'
			})
			return false;
		}
		return true;
	}

	export async function Login(): Promise<IUser> {
		let loginUser: ILoginUser = {};
		const data: wx.LoginResult = await tools.Promise(wx.login);
		if (!data.code) {
			wxService.showToast('获取用户登录信息失败');
			return;
		}
		loginUser.code = data.code;
		// try {
		// 	const location: wx.GetLocationResult = await tools.Promise(wx.getLocation);
		// 	if (location) {
		// 		loginUser.lat = location.latitude;
		// 		loginUser.lng = location.longitude;
		// 	}
		// } catch (e) {
		// 	//拒绝位置授权
		// }
		try {
			const wxUser: {
				encryptedData: string,
				iv: string,
				userInfo: {
					avatarUrl?: string,
					city?: string,
					country?: string,
					gender?: number,
					language?: string,
					nickName?: string,
					province?: string
				}
			} = await tools.Promise(wx.getUserInfo);
			if (wxUser.userInfo) {
				loginUser.encryptedData = wxUser.encryptedData;
				loginUser.iv = wxUser.iv;
				loginUser.headImgUrl = wxUser.userInfo.avatarUrl;
				loginUser.name = wxUser.userInfo.nickName;
			}
		}
		catch (e) {
			// 拒绝授权
			if (e.errMsg && e.errMsg.indexOf('fail auth deny') > -1) {
				wx.showModal({
					title: '提示',
					content: '您点击了拒绝授权，有些功能将不能使用。请10分钟后再次点击授权，或者删除小程序重新进入。'
				})
				return;
			}
		}
		try {
			const userResult = await getUserInfoByLogin(loginUser)
			if (userResult.succeed) {
				wx.setStorage({
					key: "userInfo",
					data: userResult.value
				})
				return userResult.value as IUser;
			} else {
				wxService.showToast(userResult.msg);
			}
		} catch (e) {
		}
		return loginUser as IUser;
	}

	function getUserInfoByLogin(loginUser: ILoginUser) {
		const data = {
			user:
				{
					name: loginUser.name,
					lng: loginUser.lng,
					lat: loginUser.lat,
					headImgUrl: loginUser.headImgUrl
				},
			code: loginUser.code,
			encryptedData: loginUser.encryptedData,
			iv: loginUser.iv
		};
		return httpClient.post<
			{
				name: string,
				headImgUrl: string,
				token: string
			}
			>(config.user.login_wx, data)
	}

}
